var express = require('express');
var router = express.Router();
const { loginService, registerService, updateSupplierService, getSupplierService } = require('../service/webService')
const { formatResponse, uploading, analysisToken } = require('../utils/tool')
const multer = require('multer');
const { UploadError } = require('../utils/errors');

router.post('/login', async function(req, res, next) {
  const result = await loginService(req.body)
  if (result.token) {
    res.setHeader("Authorization", result.token)
    res.send(formatResponse(result, '登录成功'))
  } else {
    res.send(formatResponse(null, '账号或密码错误', 400))
  }
});

router.get('/logout', async function(req, res, next) {
  res.setHeader("Authorization", '')
  res.send(formatResponse(null))
})

router.post('/register', async function(req, res, next) {
  const result = await registerService(req.body)
  res.send(formatResponse(result, '注册成功'))
});

router.post('/upload', async function(req, res, next) {
  uploading.single('file')(req, res, (err) => {
    if (err instanceof multer.MulterError) {
      next(new UploadError('文件上传失败'))
    } else {
      res.send(formatResponse('/uploads/' + req.file.filename))
    }
  })
});

router.post('/updateSupplier', async function(req, res, next) {
  const result = await updateSupplierService(req.body)
  res.send(formatResponse(result, '修改成功'))
});

router.get('/getUserInfo', async function(req, res, next) {
  // 1.从客户端拿到token 然后解析
  const token = analysisToken(req.get('Token'))
  const result = await getSupplierService(token)
  res.send(formatResponse(result))
});

module.exports = router;
